package it.codelair.bakekaservice.Utilities;

import it.codelair.bakekaservice.Register_activity;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;

public class NetworkCalls extends AsyncTask<String, Void, Boolean>{
	
	private String messageTesx;
	private Register_activity activity;
	
	public NetworkCalls(Register_activity activity){
		super();
		this.activity = activity;
	}

	protected Boolean doInBackground(String... urls) {
        try {
        	HttpClient httpClient = NetworkUtilities.getHttpClient();
        	HttpPost httpPost = new HttpPost(urls[0]);
        	
        	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
            nameValuePairs.add(new BasicNameValuePair("campoNascosto",""));
            nameValuePairs.add(new BasicNameValuePair("username", urls[3]));
            nameValuePairs.add(new BasicNameValuePair("password",urls[4]));
            nameValuePairs.add(new BasicNameValuePair("email",urls[5]));
            nameValuePairs.add(new BasicNameValuePair("nome",urls[1]));
            nameValuePairs.add(new BasicNameValuePair("cognome",urls[2]));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response;
			response = httpClient.execute(httpPost);
			InputStream inputStream = response.getEntity().getContent();
			byte[] data = new byte[256];

            StringBuffer buffer = new StringBuffer();
            int len = 0;
            while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
            }
            inputStream.close();
            this.messageTesx = buffer.toString();
			return true;
        } catch (Exception e) {
        	this.messageTesx = "error";
            return false;
        }
    }
	
	@Override
    protected void onPostExecute(Boolean result) {
        this.activity.createLocalAccount(this.messageTesx);
    }

	public String getMessageTesx() {
		return messageTesx;
	}

	public void setMessageTesx(String messageTesx) {
		this.messageTesx = messageTesx;
	}

	public Activity getActivity() {
		return activity;
	}

	public void setActivity(Register_activity activity) {
		this.activity = activity;
	}
   
}
